#include<unistd.h>
#include<cstdio>
#include<iostream>
#include<cassert>
#include<sys/types.h>
#include<sys/wait.h>
#include<cstdlib>
#include<cstring>
//实现一个父子通信的匿名管道
//子进程写，父进程读，并探究读写特性
int main(){
    int fds[2];
    int p = pipe(fds);
    assert(p == 0);
    pid_t id = fork();
    if(id == -1){
        perror("fork filed");
        exit(-1);
    }else if(id == 0){//子进程,关闭读fd，使用写fd，实现单向通信
        close(fds[0]);
        char buffer[1024];
        int cnt = 0;
        while(true){
            sprintf(buffer,"this is child process,now i am calling parent process,%d,%d",++cnt,getpid());
            write(fds[1],buffer,strlen(buffer));
            std::cout<<cnt<<std::endl;
            //sleep(1);
            //if(cnt == 10) break;
            //f(cnt == 9) close(fds[1]);
            sleep(1);
        }
        exit(0);
    }
    close(fds[1]);
    char buffer[1024];
    while(true){
        //sleep(1000);
        ssize_t r = read(fds[0],buffer,sizeof(buffer)-1);//预留/0结尾
        if(r > 0) buffer[r] = 0;
        fprintf(stdout,"the message from chiled is : %s\n",buffer);
        if(r == 0) break;
    }
    
    int status = 0;
    waitpid(id,&status,0);//阻塞式等待；
    return 0;
    //父进程

}
